package ccm.itesm.mx.servicios;

//import android.app.Activity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ListaMaterias extends ListActivity {
	private AndroidDAO dao;
	
	private String opciones [];
	static String matricula;
	static String JSONUNO= "http://escolares.ccm.itesm.mx/~mobile/boleta/boleta.php?mat=", 
				JSONUNOCONT="&trm=201113",
				JSONDOS= "http://escolares.ccm.itesm.mx/~mobile/boleta/grupos.php?crs=", 
				JSONDOSCONT="&trm=201113";
	private ArrayList<String> listaCrn, listaMaterias;
	private ArrayList<JSONObject> listaJson;

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.faltas);
		
		listaCrn = new ArrayList<String>();
		listaMaterias = new ArrayList<String>();
		listaJson = new ArrayList<JSONObject>();
		//opciones = new String[] {"Proyecto de Software","Redes Corporativas","Redes Inalambricas","Lenguajes de Programacion"};
		
    	this.dao = new AndroidDAO(this);
    	List<String> db = dao.selectAll();
    	
    	cargaMaterias(db.get(0));
    	
    	
		Toast.makeText(getApplicationContext(),"Bienvenido " + db.get(0), Toast.LENGTH_LONG).show();
		dao.open.close();
		this.setListAdapter(new ArrayAdapter<String>(this, R.layout.listactivity,listaMaterias));
		//this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listaCrn));
		 
	}
	
	
	/* (non-Javadoc)
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView, android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		//switch(position){
		//default:
			String prof="";
			String titulo="";
			String fechas="";
			String email="";
			try {
				prof = listaJson.get(position).getString("nombre")+
						" "+listaJson.get(position).getString("paterno")+ 
						" "+listaJson.get(position).getString("materno");
				titulo = listaJson.get(position).getString("nommat");
				 email = listaJson.get(position).getString("correo");
				fechas = "Del: "+ listaJson.get(position).getString("start_date")+
						" al: " + listaJson.get(position).getString("end_date");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			Bundle bunny = new Bundle();
			bunny.putString("prof", prof);
			bunny.putString("titulo", titulo);
			bunny.putString("email", email);
			bunny.putString("fechas", fechas);
			Intent intento = new Intent(getApplicationContext(), Materia.class);
			intento.putExtras(bunny);
			startActivityForResult(intento,0);
			//Toast.makeText(getApplicationContext(),"Prof "+ prof, Toast.LENGTH_LONG).show();
			//Toast.makeText(getApplicationContext(), ""+position, Toast.LENGTH_LONG).show();
			//this.startActivity(new Intent(this, Materia.class));
			//break;
		//}

	}
	
	private void cargaCrn(ArrayList<String> crn){
		String consulta, respuesta;
		for(int j=0; j<crn.size();j++){
			consulta = JSONDOS+crn.get(j)+JSONDOSCONT;
			respuesta = download(consulta);
			if(respuesta != null && !respuesta.startsWith("Error")){
				try {
					JSONArray principal = new JSONArray(respuesta);
					if(principal.length()>0){
						for(int i =0; i< 1;i++){
							JSONObject materiaConsulta = principal.getJSONObject(i);
							this.listaJson.add(materiaConsulta);
							this.listaMaterias.add(materiaConsulta.getString("nommat"));
						}
						
					}
					else{
						Toast.makeText(getBaseContext(), "No hay datos", Toast.LENGTH_LONG).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
				
		
	}
	private void cargaMaterias(String matricula){
		String consulta= JSONUNO+ matricula.trim()+ JSONUNOCONT;
		String respuesta=download(consulta);
		
		if(respuesta != null && !respuesta.startsWith("Error")){
			//respuesta= respuesta.substring(respuesta.indexOf('{'), respuesta.length()-1);
			try {
				JSONArray principal = new JSONArray(respuesta);
				//JSONObject resultSet = principal.getJSONObject("ResultSet");
				//JSONArray materias = principal.getJSONArray("Result");
				
				if(principal.length()>0){
					
					for(int i =0; i< principal.length();i++){
						JSONObject materiaConsulta = principal.getJSONObject(i);
						this.listaCrn.add(materiaConsulta.getString("crn"));
					}
					cargaCrn(listaCrn);
					
				}
				else{
					Toast.makeText(getBaseContext(), "No hay datos", Toast.LENGTH_LONG).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else
			Toast.makeText(getBaseContext(), respuesta, Toast.LENGTH_LONG).show();
		
	}
	
	private String download(String urlString)
    {
        InputStream in = null;
        byte[] data = null;
        URLConnection conn = null;
        try
    	{
	        URL url = new URL(urlString);
	    	conn = url.openConnection();
	        
	        if ((conn instanceof HttpURLConnection))
	        {
	    		HttpURLConnection httpConn = (HttpURLConnection) conn;
	    		httpConn.setAllowUserInteraction(false);
	    		httpConn.setInstanceFollowRedirects(true);
	    		httpConn.setRequestMethod("GET");
	    		httpConn.connect();
	
	    		if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) 
	    		{
	    			in = httpConn.getInputStream();
	    			ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    			int c;
	    			while((c = in.read()) > -1)
	                    baos.write(c);
	                data = baos.toByteArray();
	                baos.close();
	                in.close();
	                String str = new String(data);
	                return str;
	    		}
	    		else
	            {                
	    			return("Error reading data");
	            }
	        }
    	}
    	catch (Exception ex)
    	{
    		return("Error in connection");
    	}
    	finally
        {
            try
            {
                if (conn != null)
                {
                    conn = null;
                }
                if (in != null)
                {
                    in.close();
                    in = null;
                }

            }catch(IOException ex)
            {
            	return("Error: "+ex.getMessage());
            }
        }   
    	return null;
    }


}
